﻿using System;
using System.Security.Cryptography;
using System.Text;

// ReSharper disable once CheckNamespace

namespace Web.Security
{
    public class Hash
    {
        public static String Sha256(String input)
        {
            var sha256Bytes = Encoding.Default.GetBytes(input);
            var buffer = (new SHA256Managed()).ComputeHash(sha256Bytes);
            var sha256Result = string.Empty;
            foreach (var t in buffer)
            {
                sha256Result += ((t <= 0xF) ? "0" : "");
                sha256Result += t.ToString("X"); //十六进制数
            }
            return sha256Result;
        }
    }

    public static class RandomString
    {
        public static String GetRandomString(Int32 length = 16, Boolean number = true, Boolean lowercaseLetter = true,
            Boolean uppercaseLetter = true, Boolean specialSymbols = false, String customChar = null)
        {
            var buffer = new Byte[4];
            new RNGCryptoServiceProvider().GetBytes(buffer);
            var randomNumber = new Random(BitConverter.ToInt32(buffer, 0));
            var result = String.Empty;
            var characterSet = customChar;
            if (number)
            {
                characterSet += "0123456789";
            }
            if (lowercaseLetter)
            {
                characterSet += "abcdefghijklmnopqrstuvwxyz";
            }
            if (uppercaseLetter)
            {
                characterSet += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            }
            if (specialSymbols)
            {
                characterSet += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
            }
            for (var i = 0; i < length; i++)
            {
                if (characterSet != null)
                    result += characterSet.Substring(randomNumber.Next(0, characterSet.Length - 1), 1);
            }
            return result;
        }
    }
}